package com.fgs.common.imageView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.bm.library.PhotoView;
import com.fgs.common.R;
import com.fgs.common.imageView.strategy.ImageLoader;
import com.fgs.common.utils.ImageUtil;
import com.fgs.common.utils.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fgs
 * @date 2020/4/2
 * @description 查看图片
 **/
public class PictureDialog extends Dialog {
    private ViewPager viewPager;
    private TextView textView;
    private ImageView downImageView;
    private TextView downloadAllTextView;
    private String imageId;
    private PictureViewPagerAdapter pagerAdapter;
    private final List<PhotoView> photoViewList = new ArrayList<>();
    private boolean isSavePicture;
    private PhotoView mPhotoView;

    public PictureDialog(@NonNull Context context) {
        super(context, R.style.style_select_dialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_picture);


        viewPager = findViewById(R.id.dialog_picture_viewPager);
        textView = findViewById(R.id.dialog_picture_numberTextView);
        downImageView = findViewById(R.id.dialog_picture_saveImageView);
        downloadAllTextView = findViewById(R.id.dialog_picture_saveAllTextView);
        Window window = getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);

        pagerAdapter = new PictureViewPagerAdapter();
        viewPager.setAdapter(pagerAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int size = photoViewList.size();
                mPhotoView = photoViewList.get(position);

                int currentIndex = position + 1;
                textView.setText(currentIndex + "/" + size);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        downImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPhotoView != null) {
                    downloadCurrentPicture();
                    dismiss();
                }
            }
        });
        downloadAllTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPhotoView != null) {
                    downloadAllPicture();
                    dismiss();
                }
            }
        });

        if (isSavePicture) {
            downImageView.setVisibility(View.VISIBLE);
            downloadAllTextView.setVisibility(View.VISIBLE);
        } else {
            downImageView.setVisibility(View.GONE);
            downloadAllTextView.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(imageId)) {
            String[] strings = imageId.split(",");
            int length = strings.length;
            List<String> list = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                list.add(strings[i]);
            }
            if (list.size() > 0) {
                setImageUrlList(list);
            }
        }

    }

    private void downloadCurrentPicture() {
        try {
            Bitmap bitmap = ((BitmapDrawable) (mPhotoView).getDrawable()).getBitmap();
            ImageUtil.saveImageToGallery(getContext(), bitmap);
            ToastUtil.showShortToast("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showShortToast("保存失败");
        }
    }

    private void downloadAllPicture() {
        int size = photoViewList.size();
        if (size > 0) {
            try {
                for (PhotoView photoView : photoViewList) {
                    Bitmap bitmap = ((BitmapDrawable) (photoView).getDrawable()).getBitmap();
                    if (bitmap != null) {
                        ImageUtil.saveImageToGallery(getContext(), bitmap);
                    }
                    ToastUtil.showShortToast("保存成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showShortToast("保存失败");
            }
        } else {
            ToastUtil.showShortToast("保存失败");
        }
    }

    public void setCanSavePicture(boolean isSave) {
        isSavePicture = isSave;
    }

    public PictureDialog setImageId(String imageId) {
        this.imageId = imageId;
        return this;
    }

    public void setImageUrlList(List<String> list) {
        if (list != null && list.size() > 0) {
            viewPager.setOffscreenPageLimit(list.size());
            photoViewList.clear();
            int size = list.size();

            PhotoView photoView;
            for (int i = 0; i < size; i++) {

                photoView = new PhotoView(getContext());
                photoView.enable();
                photoView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });


                ImageLoader.init().loadImageWithId(photoView, list.get(i));
                photoViewList.add(photoView);
                if (i == 0) {
                    mPhotoView = photoView;
                }
            }
            textView.setText(1 + "/" + size);
            pagerAdapter.setPhotoViewList(photoViewList);
            pagerAdapter.notifyDataSetChanged();
        }
    }

    public void setImageBitmap(Bitmap bitmap) {
        if (bitmap != null) {

        }
    }

    private void saveFile(Bitmap bmp) {
        if (bmp == null) return;
        // 判断是否可以对SDcard进行操作
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {      // 获取SDCard指定目录下
//            String sdCardDir = Environment.getExternalStorageDirectory() + "/order/";
            String sdCardDir = getContext().getExternalFilesDir(null).getAbsolutePath();//30相册适配
            //目录转化成文件夹
            File dirFile = new File(sdCardDir);
            //如果不存在，那就建立这个文件夹
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            // 在SDcard的目录下创建图片文,以当前时间为其命名，注意文件后缀，若生成为JPEG则为.jpg,若为PNG则为.png
            File file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(file);
                //将bitmap（数值100表示不压缩）存储到out输出流中去，图片格式为 PNG
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        } else {
            return;
        }
    }
}
